<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="配置名称" prop="emailAccountId">
              <el-input v-model="queryParams.remark" clearable> </el-input>
            </el-form-item>
            <el-form-item label="邮箱账号" prop="emailAccountId">
              <el-select v-model="queryParams.emailAccountId" clearable>
                <el-option v-for="item in emailAccountList" :label="item.account" :value="item.id + ''"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收款账号" prop="payAccountId">
              <el-select v-model="queryParams.payAccountId" clearable>
                <el-option v-for="item in accountList" :label="item.accountName" :value="item.accountId + ''"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:EmailConfig:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:EmailConfig:edit']"
                >修改</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:EmailConfig:remove']"
                >删除</el-button
              >
            </el-col>
          </el-row>
          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="EmailConfigList" width="800" row-key="accountId" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="{ row }">
            <el-tag v-if="row.status == 1">开启</el-tag>
            <el-tag v-else type="info">关闭</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="配置名称" align="center" prop="remark" />
        <el-table-column label="邮箱账号" align="center" prop="emailAccountNames" show-overflow-tooltip />
        <el-table-column label="收款账号" align="center" prop="payAccountNames" show-overflow-tooltip />
        <el-table-column label="邮件模板" align="center" prop="templateNames" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:EmailConfig:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:EmailConfig:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>
    <!-- 添加或修改订单邮件配置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="EmailConfigFormRef" :model="form" :rules="rules" label-position="left" label-width="80px">
        <el-form-item label="配置名称" prop="remark">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="收款账号" prop="payAccountIds">
          <div class="flex items-center gap-1 flex-wrap">
            <template v-for="item in form.payAccountIds">
              <el-tag>{{
                accountList.find((item2) => item2.accountId == item)?.accountName
                  ? accountList.find((item2) => item2.accountId == item)?.accountName
                  : item
              }}</el-tag>
            </template>
            <el-button size="small" icon="Edit" type="primary" class="ml-3" @click="changePayAccount()">编辑</el-button>
          </div>
        </el-form-item>
        <el-form-item label="邮箱账号" prop="emailAccountIds">
          <div class="flex items-center gap-1 flex-wrap">
            <template v-for="item in form.emailAccountIds">
              <el-tag>{{
                emailAccountList.find((item2) => item2.id == item)?.account ? emailAccountList.find((item2) => item2.id == item)?.account : item
              }}</el-tag>
            </template>
            <el-button size="small" icon="Edit" type="primary" class="ml-3" @click="changeEmailAccount()">编辑</el-button>
          </div>
        </el-form-item>
        <el-form-item label="模板" prop="templateId">
          <el-select v-model="form.templateId" filterable>
            <el-option v-for="item in tempList" :label="item.name" :value="item.templateId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="选择收款账号" v-model="payAccountVisible" width="1200" append-to-body>
      <el-form ref="queryFormRef" :model="payAccQuery" :inline="true">
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="payAccQuery.accountName" placeholder="请输入账号名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="支付平台" prop="payTypeId">
          <el-select v-model="payAccQuery.payTypeId" clearable>
            <el-option v-for="item in payList" :key="item.name" :label="item.name" :value="item.typeId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="PayAccountList" ref="payAccountRef" row-key="accountId" @cell-click="selectPayAcc">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="支付平台/域名" align="center" prop="payTypeId">
          <template #default="{ row }">
            <div>{{ payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId }}</div>
            <div>{{ row.domain }}</div>
          </template>
        </el-table-column>
        <el-table-column label="API模式" align="center" prop="apiType" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-if="row.apiType" type="primary" class="truncate overflow-hidden max-w-[100%] w-fit" style="justify-content: flex-start">{{
              row.payConfig.apiConfig?.find((item) => item.value == row.apiType).label
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="70" prop="status">
          <template #default="{ row }">
            <el-tag v-if="row.status == 1" type="success">活跃</el-tag>
            <el-tag v-else type="danger">封禁</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button type="primary" @click="submitPayAcc">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="选择邮箱账号" v-model="emailAccountVisible" width="1200" append-to-body>
      <el-form ref="queryFormRef" :model="emailAccQuery" :inline="true">
        <el-form-item label="商户名称" prop="account">
          <el-input v-model="emailAccQuery.createName" placeholder="请输入商户名称" />
        </el-form-item>
        <el-form-item label="邮箱账号" prop="account">
          <el-input v-model="emailAccQuery.account" placeholder="请输入邮箱账号" />
        </el-form-item>
      </el-form>
      <el-table :data="emailAccountData" ref="emailAccountRef" @cell-click="selectEmail" row-key="id">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="商户名称" align="center" prop="createName" />
        <el-table-column label="邮箱账号" align="center" prop="account" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="email_account_status" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button type="primary" @click="submitEmailAcc">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmailConfig" lang="ts">
import { listPayAccount } from '@/api/pay/PayAccount';
import { emailConfig } from '@/api/email/EmailConfig';
import { listEmailConfig, getEmailConfig, delEmailConfig, addEmailConfig, updateEmailConfig } from '@/api/system/EmailConfig';
import { EmailConfigVO, EmailConfigQuery, EmailConfigForm } from '@/api/system/EmailConfig/types';
import { listEmailAccount } from '@/api/email/EmailAccount.js';
import { selecTypetList } from '@/api/pay/PayType/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
console.log(proxy?.animate.searchAnimate.enter, 'proxy?.animate.searchAnimate.enter');

const { email_account_status } = toRefs(proxy?.useDict('email_account_status'));

const EmailConfigList = ref<EmailConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const EmailConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EmailConfigForm = {
  configId: undefined,
  status: 0,
  emailAccountId: undefined,
  payAccountId: undefined,
  templateId: undefined
};
const data = reactive<PageData<EmailConfigForm, EmailConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    configId: undefined,
    status: undefined,
    emailAccountId: undefined,
    payAccountId: undefined,
    templateId: undefined,
    createId: undefined,
    params: {}
  },
  rules: {
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    emailAccountIds: [{ required: true, message: '邮箱账号不能为空', trigger: 'blur' }],
    payAccountIds: [{ required: true, message: '收款账号不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '配置名称不能为空', trigger: 'blur' }],
    templateId: [{ required: true, message: '邮件模板不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单邮件配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEmailConfig(queryParams.value);
  EmailConfigList.value = res.rows.map((item) => {
    item.payAccountNames = [];
    item.emailAccountNames = [];
    let payAcclist = item.payAccountId.split(',');
    let emailAccList = item.emailAccountId.split(',');
    item.emailAccountNames = emailAccList.map((item2) => {
      if (emailAccountList.value.find((item3) => item3.id == item2)?.account) {
        return emailAccountList.value.find((item3) => item3.id == item2)?.account;
      }
    });
    item.emailAccountNames = item.emailAccountNames.join(',');

    item.payAccountNames = payAcclist.map((item2) => {
      if (accountList.value.find((item3) => item3.accountId == item2)?.accountName) {
        return accountList.value.find((item3) => item3.accountId == item2)?.accountName;
      }
    });
    item.payAccountNames = item.payAccountNames.join(',');

    item.templateNames = tempList.value.find((item2) => item2.templateId == item.templateId)?.name;

    return item;
  });
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  EmailConfigFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: EmailConfigVO[]) => {
  ids.value = selection.map((item) => item.configId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加订单邮件配置';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: EmailConfigVO) => {
  reset();
  const _configId = row?.configId || ids.value[0];
  const res = await getEmailConfig(_configId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改订单邮件配置';
  form.value.payAccountIds = res.data.payAccountId.split(',');
  form.value.emailAccountIds = res.data.emailAccountId.split(',');
};

/** 提交按钮 */
const submitForm = () => {
  EmailConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.payAccountId = form.value.payAccountIds.join(',');
      form.value.emailAccountId = form.value.emailAccountIds.join(',');
      if (form.value.configId) {
        await updateEmailConfig(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addEmailConfig(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: EmailConfigVO) => {
  const _configIds = row?.configId || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单邮件配置编号为"' + _configIds + '"的数据项？').finally(() => (loading.value = false));
  await delEmailConfig(_configIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/EmailConfig/export',
    {
      ...queryParams.value
    },
    `EmailConfig_${new Date().getTime()}.xlsx`
  );
};

const tempList = ref([]);
const getTemplateList = async () => {
  let res = await emailConfig();
  tempList.value = res.data.templates;
};

const accountList = ref([]);
const getAccounts = async () => {
  await getPayList();
  let res = await listPayAccount({ pageSize: 1000, pageNum: 1 });
  accountList.value = res.rows.map((item) => {
    item.payConfig = payList.value.find((payType) => payType.typeId == item.payTypeId)?.config
      ? JSON.parse(payList.value.find((payType) => payType.typeId == item.payTypeId)?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''))
      : '';
    return item;
  });
};
const payAccQuery = ref({
  accountName: '',
  payTypeId: ''
});
const PayAccountList = computed(() => {
  let arr = accountList.value;

  if (payAccQuery.value.accountName) {
    arr = arr.filter((item) => item.accountName.includes(payAccQuery.value.accountName));
  }
  if (payAccQuery.value.payTypeId) {
    arr = arr.filter((item) => item.payTypeId == payAccQuery.value.payTypeId);
  }
  return arr;
});
const payAccountVisible = ref(false);
const payAccountRef = ref(null);
const selectPayAcc = (row) => {
  payAccountRef.value!.toggleRowSelection(row);
};
const changePayAccount = async () => {
  payAccountVisible.value = true;
  let arr = accountList.value.filter((item) => form.value.payAccountIds.find((item2) => item.accountId == item2));
  await nextTick();
  arr.forEach((item) => {
    payAccountRef.value!.toggleRowSelection(item, true, false);
  });
};
const submitPayAcc = () => {
  let arr = payAccountRef.value.getSelectionRows();
  form.value.payAccountIds = arr.map((item) => {
    return item.accountId;
  });
  payAccountVisible.value = false;
};
const handleSelectionChangePayAccount = (val) => {};
const payList = ref([]);
const getPayList = async () => {
  let res = await selecTypetList();
  payList.value = res.data;
};

const emailAccountList = ref([]);
const getEmailAccounts = async () => {
  let res = await listEmailAccount({ pageSize: 1000, pageNum: 1 });
  emailAccountList.value = res.rows;
};
const emailAccQuery = ref({
  createName: '',
  account: ''
});
const emailAccountData = computed(() => {
  let arr = emailAccountList.value;
  if (emailAccQuery.value.createName) {
    arr = arr.filter((item) => item.createName.includes(emailAccQuery.value.createName));
  }
  if (emailAccQuery.value.account) {
    arr = arr.filter((item) => item.account == emailAccQuery.value.account);
  }
  return arr;
});
const emailAccountVisible = ref(false);
const emailAccountRef = ref(null);
const selectEmail = (row) => {
  emailAccountRef.value!.toggleRowSelection(row);
};
const changeEmailAccount = async () => {
  emailAccountVisible.value = true;
  let arr = emailAccountList.value.filter((item) => form.value.emailAccountIds.find((item2) => item.id == item2));
  await nextTick();
  arr.forEach((item) => {
    emailAccountRef.value!.toggleRowSelection(item);
  });
};
const submitEmailAcc = () => {
  let arr = emailAccountRef.value.getSelectionRows();
  form.value.emailAccountIds = arr.map((item) => {
    return item.id;
  });
  emailAccountVisible.value = false;
};
onMounted(async () => {
  await getTemplateList();
  await getAccounts();
  await getEmailAccounts();
  getList();
});
</script>
